<?php
/**
 * Work in progress.
 */

class ActiveResource
{
	public    $id;
	
	protected $_site;
	protected $_format  = 'application/json';
	protected $_options = array(
		'connecttimeout' => 10,
		'timeout'        => 20,
		'headers'        => array(
			'HTTP_ACCEPT_CHARSET' => Core::charset,
		)
	);
	
	function construct($id=null)
	{
		# exchange _format
		$this->_options['headers']['Content-Type'] = $this->_format;
		$this->_options['headers']['HTTP_ACCEPT']  = $this->_format;
		
		# this
		if (!empty($id))
			$this->read($id);
	}
	
	function set(array &$data)
	{
		foreach($data as $k => $v)
			$this->$k =& $v;
	}
	
	function get($id=null)
	{
		if (!is_null($id))
			$this->id = $id;
		
		$rq = new HttpRequest($this->_site.'/'.$this->id, HttpRequest::METH_GET, $this->_options);
		$rq->send();
		
		if ($rq->getResponseCode() != 200)
			throw new Exception($rq->getResponseCode(), $rq->getResponseStatus());
		
		$this->set($this->decodeData($rq->getResponseBody()));
	}
	
	function & getAll()
	{
		$rq = new HttpRequest($this->_site, HttpRequest::METH_GET, $this->_options);
		$rq->send();
		
		if ($rq->getResponseCode() != 200)
			throw new Exception($rq->getResponseCode(), $rq->getResponseStatus());
		
		$data  = $this->decodeData($rq->getResponseBody());
		$class = get_class($this);
		
		foreach($data as $i => $d)
		{
			$data[$i] = new $class();
			$data[$i]->set($d);
		}
		
		return $data;
	}
	
	function create()
	{
		$rq = new HttpRequest($this->_site, HttpRequest::METH_POST, $this->_options);
		$rq->setPostData($this->encodeData($this->data));
		$rq->send();
		
		if ($rq->getResponseCode() != 201)
		{
			$this->validationErrors = $this->decodeData($rq->getResponseBody());
			throw new Exception($rq->getResponseCode(), $rq->getResponseStatus());
		}
		$this->id = $rq->getResponseBody();
	}
	
	function update()
	{
		$rq = new HttpRequest($this->_site.'/'.$this->id, HttpRequest::METH_PUT, $this->_options);
		$rq->setPutData($this->encodeData($this->data));
		$rq->send();
		
		if ($rq->getResponseCode() != 200)
		{
			$this->validationErrors = $this->decodeData($rq->getResponseBody());
			throw new Exception($rq->getResponseCode(), $rq->getResponseStatus());
		}
	}
	
	function delete()
	{
		$rq = new HttpRequest($this->_site.'/'.$this->id, HttpRequest::METH_DELETE, $this->_options);
		$rq->send();
		
		if ($rq->getResponseCode() != 204) {
			throw new Exception($rq->getResponseCode(), $rq->getResponseBody());
		}
	}
	
	// internals
	
	protected function encodeData(&$data)
	{
		switch($this->_format)
		{
			case 'application/json': return json_encode($data);
			default: trigger_error("Unknown mimetype: {$this->_format}", E_USER_ERROR);
		}
	}
	
	protected function & decodeData($data)
	{
		switch($this->_format)
		{
			case 'application/json': return json_decode($data);
			default: trigger_error("Unknown mimetype: {$this->_format}", E_USER_ERROR);
		}
	}
}
?>
